package com.sxfq.loansupermarket.backsystem.modular.arrival.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.MsgSendInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SmsTemplateInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.MedicalAdviceInfo;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/msgSend")
public class MsgSendController extends BaseController {
    @Autowired
    private MemberProductService memberProductService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/arrival/customer/";

    private String PREFIY = "/marketing/reservations/";

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAIQMzfyJwlbjuU";

    static final String accessKeySecret = "8yCe7fywBbBkZbMS8dXkS2tZpELT6N";

    /**
     * 跳转到发送短信
     */
    @RequestMapping("/to_msgSend/{customerId}")
    public String to_msgSend(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select ( " +
                " CASE t.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex,t.* from " + ShiroKit.getUser().getCustomer_info() + " t where id='" + customerId + "' limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String sql22 = "select * from dept where abbreviation='" + tableHead + "'";
        //短信一级模板
        String oneCode = "select distinct one_class as oneClass from sms_template_code ";
        List<SmsTemplateInfo> infoList = sqlMapper.selectList(oneCode,SmsTemplateInfo.class);
        Map<String, Object> mapList = new HashMap<String, Object>();
        for(SmsTemplateInfo info : infoList ){
            String twoCodesql = "select id,two_class as twoClass from sms_template_code where one_class= '"+info.getOneClass()+"'";
            List<SmsTemplateInfo> infos = sqlMapper.selectList(twoCodesql,SmsTemplateInfo.class);
            List<SmsTemplateInfo> list = new ArrayList<SmsTemplateInfo>();
            for(SmsTemplateInfo infoTwo : infos){
                list.add(infoTwo);
            }
            mapList.put(info.getOneClass(),list);
        }
        model.addAttribute("mapList", mapList);
        Dept dept = sqlMapper.selectOne(sql22, Dept.class);
        model.addAttribute("deptInfo", dept);
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("startTime", customerInfo.getStartTime().substring(0, 19));
        model.addAttribute("doctor", customerInfo.getDoctor());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIX + "to_msgSend.html";
    }

    /**
     * 跳转到发送短信
     */
    @RequestMapping("/to_msgSend2/{customerId}")
    public String to_msgSend2(@PathVariable String customerId, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select ( " +
                " CASE t.customer_sex " +
                "  WHEN 1 THEN " +
                "   '男' " +
                "  WHEN 2 THEN " +
                "   '女' " +
                "  ELSE " +
                "   '未知' " +
                "  END " +
                "  ) as sex,t.* from " + ShiroKit.getUser().getCustomer_info() + " t where id='" + customerId + "' limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String sql22 = "select * from dept where abbreviation='" + tableHead + "'";
        Dept dept = sqlMapper.selectOne(sql22, Dept.class);
        //短信一级模板
        String oneCode = "select distinct one_class as oneClass from sms_template_code ";
        List<SmsTemplateInfo> infoList = sqlMapper.selectList(oneCode,SmsTemplateInfo.class);
        Map<String, Object> mapList = new HashMap<String, Object>();
        for(SmsTemplateInfo info : infoList ){
            String twoCodesql = "select id,two_class as twoClass from sms_template_code where one_class= '"+info.getOneClass()+"'";
            List<SmsTemplateInfo> infos = sqlMapper.selectList(twoCodesql,SmsTemplateInfo.class);
            List<SmsTemplateInfo> list = new ArrayList<SmsTemplateInfo>();
            for(SmsTemplateInfo infoTwo : infos){
                list.add(infoTwo);
            }
            mapList.put(info.getOneClass(),list);
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("deptInfo", dept);
        model.addAttribute("customerId", customerId);
        model.addAttribute("customerInfo", customerInfo);
        model.addAttribute("startTime", customerInfo.getStartTime().substring(0, 19));
        model.addAttribute("doctor", customerInfo.getDoctor());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIX + "to_msgSend_two.html";
    }

    /**
     * 市场跳转到发送短信
     */
    @RequestMapping("/to_market_msgSend/{id}")
    public String to_msgMarketSend(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select ( " +
                "        CASE t.customer_sex " +
                "        WHEN 1 THEN " +
                "        '男' " +
                "        WHEN 2 THEN " +
                "        '女' " +
                "        ELSE " +
                "        '未知' " +
                "        END " +
                "        ) as sex,t.* from reservations_infosc t where id='" + id + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        String sql22 = "select * from dept where abbreviation='" + tableHead + "'";
        Dept dept = sqlMapper.selectOne(sql22, Dept.class);
        //短信一级模板
        String oneCode = "select distinct one_class as oneClass from sms_template_code ";
        List<SmsTemplateInfo> infoList = sqlMapper.selectList(oneCode,SmsTemplateInfo.class);
        Map<String, Object> mapList = new HashMap<String, Object>();
        for(SmsTemplateInfo info : infoList ){
            String twoCodesql = "select id,two_class as twoClass from sms_template_code where one_class= '"+info.getOneClass()+"'";
            List<SmsTemplateInfo> infos = sqlMapper.selectList(twoCodesql,SmsTemplateInfo.class);
            List<SmsTemplateInfo> list = new ArrayList<SmsTemplateInfo>();
            for(SmsTemplateInfo infoTwo : infos){
                list.add(infoTwo);
            }
            mapList.put(info.getOneClass(),list);
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("deptInfo", dept);
        model.addAttribute("reservationsId", id);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("startTime", reservationsInfo.getAppointmentArrivalTime().substring(0, 10));
        model.addAttribute("doctor", reservationsInfo.getDoctor());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIY + "to_market_msgSend.html";
    }

    /**
     * 市场跳转到发送短信
     */
    @RequestMapping("/to_market_msgSend2/{id}")
    public String to_msgMarketSend2(@PathVariable String id, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select ( " +
                "        CASE t.customer_sex " +
                "        WHEN 1 THEN " +
                "        '男' " +
                "        WHEN 2 THEN " +
                "        '女' " +
                "        ELSE " +
                "        '未知' " +
                "        END " +
                "        ) as sex,t.* from reservations_infosc t where id='" + id + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        String sql22 = "select * from dept where abbreviation='" + tableHead + "'";
        Dept dept = sqlMapper.selectOne(sql22, Dept.class);
        //短信一级模板
        String oneCode = "select distinct one_class as oneClass from sms_template_code ";
        List<SmsTemplateInfo> infoList = sqlMapper.selectList(oneCode,SmsTemplateInfo.class);
        Map<String, Object> mapList = new HashMap<String, Object>();
        for(SmsTemplateInfo info : infoList ){
            String twoCodesql = "select id,two_class as twoClass from sms_template_code where one_class= '"+info.getOneClass()+"'";
            List<SmsTemplateInfo> infos = sqlMapper.selectList(twoCodesql,SmsTemplateInfo.class);
            List<SmsTemplateInfo> list = new ArrayList<SmsTemplateInfo>();
            for(SmsTemplateInfo infoTwo : infos){
                list.add(infoTwo);
            }
            mapList.put(info.getOneClass(),list);
        }
        model.addAttribute("mapList", mapList);
        model.addAttribute("deptInfo", dept);
        model.addAttribute("reservationsId", id);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("startTime", reservationsInfo.getAppointmentArrivalTime().substring(0, 10));
        model.addAttribute("doctor", reservationsInfo.getDoctor());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        return PREFIY + "to_market_msgSend2.html";
    }

    /**
     * 推送预约消息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/sendAppointmentMessage", method = RequestMethod.POST)
    @ResponseBody
    public int sendAppointmentMessage(String treatmentUnit, String projectData, String doctor, String startTimeValue, String reservationsId, String customerPhone) throws ClientException, InterruptedException {
        String selsql = "select open_id,name,medical_record_number from members_user where account='" + customerPhone + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        if (membersUser != null) {
            return memberProductService.sendAppointmentMessage(membersUser.getOpenId(), treatmentUnit, projectData, doctor, membersUser.getMedicalRecordNumber(),
                    membersUser.getName(), startTimeValue, reservationsId, customerPhone);
        } else {
            return 0;
        }
    }

//    /**
//     * 推送调查问卷
//     *
//     * @return
//     */
//    @RequestMapping(value = "/sendQuestionnaire", method = RequestMethod.POST)
//    public int sendQuestionnaire() throws ClientException, InterruptedException {
//        String selsql = "select open_id from members_user where account='18986439884' limit 1";
//        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
//        if (membersUser != null) {
//            return memberProductService.sendQuestionnaire(membersUser.getOpenId());
//        } else {
//            return 0;
//        }
//    }

    /**
     * 推送术后医嘱
     *
     * @param medicalAdviceUnit
     * @return
     */
    @RequestMapping(value = "/sendMedicalAdvice", method = RequestMethod.POST)
    @ResponseBody
    public int sendMedicalAdvice(String medicalAdviceUnit, String doctor, String customerPhone) throws ClientException, InterruptedException {
        String medicalAdviceTitle = "";
        String medicalAdviceContent = "";
        if (ShiroKit.getSessionAttr(medicalAdviceUnit + "medicalAdviceTitle") == null || ShiroKit.getSessionAttr(medicalAdviceUnit + "medicalAdviceContent") == null) {
            String sql = "select * from medical_advice_info where medical_advice_unit='" + medicalAdviceUnit + "'";
            MedicalAdviceInfo medicalAdviceInfo = sqlMapper.selectOne(sql, MedicalAdviceInfo.class);
            ShiroKit.setSessionAttr(medicalAdviceUnit + "medicalAdviceTitle", medicalAdviceInfo.getMedicalAdviceTitle());
            ShiroKit.setSessionAttr(medicalAdviceUnit + "medicalAdviceContent", medicalAdviceInfo.getMedicalAdviceContent());
        }
        String selsql = "select open_id from members_user where account='" + customerPhone + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        if (membersUser != null) {
            medicalAdviceTitle = ShiroKit.getSessionAttr(medicalAdviceUnit + "medicalAdviceTitle");
            medicalAdviceContent = ShiroKit.getSessionAttr(medicalAdviceUnit + "medicalAdviceContent");
            return memberProductService.sendMedicalAdviceMessage(membersUser.getOpenId(), doctor, medicalAdviceTitle, medicalAdviceContent);
        } else {
            return 0;
        }
    }
    /**
     * 短信模板
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/codeList", method = RequestMethod.POST)
    @ResponseBody
    public SmsTemplateInfo smsCodeList(String context,String customerName,String outpatientName,String address,String phone,String transportation,String time,String doctor){
        String sqlList = "select * from sms_template a left join sms_parameter b on a.sms_parameter_id = b.id where template_name ='"+context+"' ";
        SmsTemplateInfo info  = sqlMapper.selectOne(sqlList,SmsTemplateInfo.class);
        String contextCode = info.getContext();
        if(contextCode.contains("phone")){
            contextCode=contextCode.replace("phone",""+phone+"");
        }
        if(contextCode.contains("outpatientName")){
            contextCode = contextCode.replace("outpatientName",""+outpatientName+"");
        }
        if(contextCode.contains("customerName")){
            contextCode = contextCode.replace("customerName",""+customerName+"");
        }
        if(contextCode.contains("address")){
            contextCode = contextCode.replace("address",""+address+"");
        }
        if(contextCode.contains("transportation")){
            contextCode = contextCode.replace("transportation",""+transportation+"");
        }
        if(contextCode.contains("time")){
            contextCode = contextCode.replace("time",""+time+"");
        }
        if(contextCode.contains("doctor")){
            contextCode = contextCode.replace("doctor",""+doctor+"");
        }
        info.setContext(contextCode);
        return info;
    }


    /**
     * 患者到店
     *
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/msgSend", method = RequestMethod.POST)
    @ResponseBody
    public int msgSend(String customerId, String smsParameterId,String messageContent, String customerPhone, String outpatientName, String templateCode, String address, String transportation, String phone, String customerName, String time, String doctor) throws ClientException, InterruptedException {
        String sql = "select * from " + ShiroKit.getUser().getCustomer_info() + " where id='" + customerId + "' limit 0,1";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        String signName = "钛植口腔" + ShiroKit.getUser().getOutpatientName();
        String phoneNumbers = "";
        try {
            phoneNumbers = customerPhone.substring(0, 11);
        } catch (Exception e) {
            return -1;
        }
        //String TemplateParam = "";
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumbers);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //    request.setTemplateParam("{\"address\":\""+address+"\",\"outpatientName\":\""+outpatientName+"\",\"phone\":\""+phone+"\",\"customerName\":\""+customerName+"\",\"time\":\""+time+"\",\"doctor\":\""+doctor+"\",\"transportation\":\""+transportation+"\" } ");
        if("1".equals(smsParameterId)){
            request.setTemplateParam("{\"phone\":\"" + phone + "\"} ");
        }
        if("2".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("3".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("4".equals(smsParameterId)){
            request.setTemplateParam("{\"time\":\"" + time + "\",\"doctor\":\"" + doctor + "\",\"phone\":\"" + phone + "\",\"outpatientName\":\"" + outpatientName + "\"} ");
        }
        if("5".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("6".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\"} ");
        }
        if("7".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"customerName\":\"" + customerName + "\"} ");
        }
        if("8".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("9".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\"} ");
        }
        if("10".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"address\":\"" + address + "\",\"transportation\":\"" + transportation + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("11".equals(smsParameterId)){
            request.setTemplateParam("");
        }
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("123");
        //发短信
        SendSmsResponse response = sendSms(request);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(300L);
        //查明细
        if (response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
                System.out.println("SmsSendDetailDTO[" + i + "]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
            String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`, `outpatient_name`, `is_success`) VALUES" +
                    "('" + ShiroKit.getUser().getAccount() + "', '" + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "', '" + messageContent + "','" + ShiroKit.getUser().getOutpatientName() + "',1);";
            return sqlMapper.insert(insertsql);
        } else {
            String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`,`outpatient_name`, `is_success`) VALUES" +
                    "('" + ShiroKit.getUser().getAccount() + "', '" + customerInfo.getCustomerName() + "', '" + customerInfo.getCustomerPhone() + "', '" + messageContent + "','" + ShiroKit.getUser().getOutpatientName() + "',2);";
            return sqlMapper.insert(insertsql);
        }
    }

    /**
     * 患者到店群发
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/msgSend2", method = RequestMethod.POST)
    @ResponseBody
    public int msgSend2(@RequestBody MsgSendInfo messageData) throws ClientException, InterruptedException {
        String messageContent = messageData.getMessageContent();
        String templateCode = messageData.getTemplateCode();
        String smsParameterId = messageData.getSmsParameterId();
        String signName = "";
        String phone = "";
        String phoneNumbers = "";
        String address = "";
        String outpatientName = "";
        String customerName = "";
        String time = "";
        String doctor = "";
        String transportation = "";
        for (int i = 0; i < messageData.getPatientList().size(); i++) {
            signName = "钛植口腔" + messageData.getPatientList().get(i).getOutpatientName();
            phone = messageData.getPatientList().get(i).getPhones();
            try {
                phoneNumbers = messageData.getPatientList().get(i).getCustomerPhone().substring(0, 11);
            } catch (StringIndexOutOfBoundsException e) {
                continue;
            }
            address = messageData.getPatientList().get(i).getDeptAddress();
            outpatientName = messageData.getPatientList().get(i).getOutpatientName();
            customerName = messageData.getPatientList().get(i).getCustomerName();
            time = messageData.getPatientList().get(i).getTime().substring(0, 11);
            doctor = messageData.getPatientList().get(i).getDoctor();
            transportation = messageData.getPatientList().get(i).getTransportation();
            //String TemplateParam = "";
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(phoneNumbers);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
            if("1".equals(smsParameterId)){
                request.setTemplateParam("{\"phone\":\"" + phone + "\"} ");
            }
            if("2".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("3".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("4".equals(smsParameterId)){
                request.setTemplateParam("{\"time\":\"" + time + "\",\"doctor\":\"" + doctor + "\",\"phone\":\"" + phone + "\",\"outpatientName\":\"" + outpatientName + "\"} ");
            }
            if("5".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("6".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\"} ");
            }
            if("7".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"customerName\":\"" + customerName + "\"} ");
            }
            if("8".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("9".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\"} ");
            }
            if("10".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"address\":\"" + address + "\",\"transportation\":\"" + transportation + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("11".equals(smsParameterId)){
                request.setTemplateParam("");
            }
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("123");
            //发短信
            SendSmsResponse response = sendSms(request);
            System.out.println("短信接口返回的数据----------------");
            System.out.println("Code=" + response.getCode());
            System.out.println("Message=" + response.getMessage());
            System.out.println("RequestId=" + response.getRequestId());
            System.out.println("BizId=" + response.getBizId());
            Thread.sleep(300L);
            //查明细
            if (response.getCode() != null && response.getCode().equals("OK")) {
                QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
                System.out.println("短信明细查询接口返回数据----------------");
                System.out.println("Code=" + querySendDetailsResponse.getCode());
                System.out.println("Message=" + querySendDetailsResponse.getMessage());
                for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
                    System.out.println("SmsSendDetailDTO[" + i + "]:");
                    System.out.println("Content=" + smsSendDetailDTO.getContent());
                    System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                    System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                    System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                    System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                    System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                    System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                    System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
                }
                String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`, `outpatient_name`, `is_success`) VALUES" +
                        "('" + ShiroKit.getUser().getAccount() + "', '" + customerName + "', '" + phoneNumbers + "', '" + messageContent + "','" + outpatientName + "',1);";
                sqlMapper.insert(insertsql);
            } else {
                String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`,`outpatient_name`, `is_success`) VALUES" +
                        "('" + ShiroKit.getUser().getAccount() + "', '" + customerName + "', '" + phoneNumbers + "', '" + messageContent + "','" + outpatientName + "',2);";
                sqlMapper.insert(insertsql);
            }
        }
        return 1;
    }

    /**
     * 市场发短信
     *
     * @param reservationsId
     * @return
     */
    @RequestMapping(value = "/msgMarketSend", method = RequestMethod.POST)
    @ResponseBody
    public int msgMarketSend(String reservationsId,String smsParameterId, String messageContent, String customerPhone, String outpatientName, String templateCode, String address, String phone, String customerName, String time, String doctor, String transportation) throws ClientException, InterruptedException {
        String sql = "select * from reservations_infosc where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        String signName = "钛植口腔" + ShiroKit.getUser().getOutpatientName();
        String phoneNumbers = customerPhone;
        //String TemplateParam = "";
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumbers);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        if("1".equals(smsParameterId)){
            request.setTemplateParam("{\"phone\":\"" + phone + "\"} ");
        }
        if("2".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("3".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("4".equals(smsParameterId)){
            request.setTemplateParam("{\"time\":\"" + time + "\",\"doctor\":\"" + doctor + "\",\"phone\":\"" + phone + "\",\"outpatientName\":\"" + outpatientName + "\"} ");
        }
        if("5".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("6".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\"} ");
        }
        if("7".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"customerName\":\"" + customerName + "\"} ");
        }
        if("8".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("9".equals(smsParameterId)){
            request.setTemplateParam("{\"customerName\":\"" + customerName + "\"} ");
        }
        if("10".equals(smsParameterId)){
            request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"address\":\"" + address + "\",\"transportation\":\"" + transportation + "\",\"phone\":\"" + phone + "\"} ");
        }
        if("11".equals(smsParameterId)){
            request.setTemplateParam("");
        }
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("123");
        //发短信
        SendSmsResponse response = sendSms(request);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(300L);
        //查明细
        if (response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
                System.out.println("SmsSendDetailDTO[" + i + "]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
            String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`, `outpatient_name`, `is_success`) VALUES" +
                    "('" + ShiroKit.getUser().getAccount() + "', '" + reservationsInfo.getCustomerName() + "', '" + reservationsInfo.getCustomerPhone() + "', '" + messageContent + "','" + ShiroKit.getUser().getOutpatientName() + "',1);";
            return sqlMapper.insert(insertsql);
        } else {
            String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`,`outpatient_name`, `is_success`) VALUES" +
                    "('" + ShiroKit.getUser().getAccount() + "', '" + reservationsInfo.getCustomerName() + "', '" + reservationsInfo.getCustomerPhone() + "', '" + messageContent + "','" + ShiroKit.getUser().getOutpatientName() + "',2);";
            return sqlMapper.insert(insertsql);
        }
    }

    /**
     * 市场发短信2
     *
     * @param messageData
     * @return
     */
    @RequestMapping(value = "/msgMarketSend2", method = RequestMethod.POST)
    @ResponseBody
    public int msgMarketSend2(@RequestBody MsgSendInfo messageData) throws ClientException, InterruptedException {
        String messageContent = messageData.getMessageContent();
        String templateCode = messageData.getTemplateCode();
        String smsParameterId = messageData.getSmsParameterId();
        String signName = "";
        String phone = "";
        String phoneNumbers = "";
        String address = "";
        String outpatientName = "";
        String customerName = "";
        String time = "";
        String doctor = "";
        String transportation = "";
        for (int i = 0; i < messageData.getPatientList().size(); i++) {
            signName = "钛植口腔" + messageData.getPatientList().get(i).getOutpatientName();
            phone = messageData.getPatientList().get(i).getPhones();
            phoneNumbers = messageData.getPatientList().get(i).getCustomerPhone();
            address = messageData.getPatientList().get(i).getDeptAddress();
            outpatientName = messageData.getPatientList().get(i).getOutpatientName();
            customerName = messageData.getPatientList().get(i).getCustomerName();
            time = messageData.getPatientList().get(i).getAppointmentTime().substring(0, 11);
            doctor = messageData.getPatientList().get(i).getDoctor();
            transportation = messageData.getPatientList().get(i).getTransportation();
            //String TemplateParam = "";
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(phoneNumbers);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
            if("1".equals(smsParameterId)){
                request.setTemplateParam("{\"phone\":\"" + phone + "\"} ");
            }
            if("2".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("3".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("4".equals(smsParameterId)){
                request.setTemplateParam("{\"time\":\"" + time + "\",\"doctor\":\"" + doctor + "\",\"phone\":\"" + phone + "\",\"outpatientName\":\"" + outpatientName + "\"} ");
            }
            if("5".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"time\":\"" + time + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("6".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\"} ");
            }
            if("7".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"customerName\":\"" + customerName + "\"} ");
            }
            if("8".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\",\"outpatientName\":\"" + outpatientName + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("9".equals(smsParameterId)){
                request.setTemplateParam("{\"customerName\":\"" + customerName + "\"} ");
            }
            if("10".equals(smsParameterId)){
                request.setTemplateParam("{\"outpatientName\":\"" + outpatientName + "\",\"address\":\"" + address + "\",\"transportation\":\"" + transportation + "\",\"phone\":\"" + phone + "\"} ");
            }
            if("11".equals(smsParameterId)){
                request.setTemplateParam("");
            }
            //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("123");
            //发短信
            SendSmsResponse response = sendSms(request);
            System.out.println("短信接口返回的数据----------------");
            System.out.println("Code=" + response.getCode());
            System.out.println("Message=" + response.getMessage());
            System.out.println("RequestId=" + response.getRequestId());
            System.out.println("BizId=" + response.getBizId());
            Thread.sleep(300L);
            //查明细
            if (response.getCode() != null && response.getCode().equals("OK")) {
                QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
                System.out.println("短信明细查询接口返回数据----------------");
                System.out.println("Code=" + querySendDetailsResponse.getCode());
                System.out.println("Message=" + querySendDetailsResponse.getMessage());
                for (QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) {
                    System.out.println("SmsSendDetailDTO[" + i + "]:");
                    System.out.println("Content=" + smsSendDetailDTO.getContent());
                    System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                    System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                    System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                    System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                    System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                    System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                    System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
                }
                String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`, `outpatient_name`, `is_success`) VALUES" +
                        "('" + ShiroKit.getUser().getAccount() + "', '" + customerName + "', '" + phoneNumbers + "', '" + messageContent + "','" + outpatientName + "',1);";
                sqlMapper.insert(insertsql);
            } else {
                String insertsql = "INSERT INTO `msg_send_info` ( `sender`, `customer_name`, `customer_phone`, `message_content`,`outpatient_name`, `is_success`) VALUES" +
                        "('" + ShiroKit.getUser().getAccount() + "', '" + customerName + "', '" + phoneNumbers + "', '" + messageContent + "','" + outpatientName + "',2);";
                sqlMapper.insert(insertsql);
            }
        }
        return 1;
    }

    public static SendSmsResponse sendSms(SendSmsRequest request) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

    public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("18602744660");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);
        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        return querySendDetailsResponse;
    }


//    public  class TimerManager {
//        //时间间隔
//        private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
//        public  TimerManager() {
//            Calendar calendar = Calendar.getInstance();
//            /*** 定制每日8:00执行方法 ***/
//            calendar.set(Calendar.HOUR_OF_DAY, 11);
//            calendar.set(Calendar.MINUTE, 23);
//            calendar.set(Calendar.SECOND, 0);
//            Date date = calendar.getTime(); //第一次执行定时任务的时间
//            System.out.println(date);
//            System.out.println("before 方法比较：" + date.before(new Date()));
//            //如果第一次执行定时任务的时间 小于 当前的时间
//            //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。循环执行的周期则以当前时间为准
//            if (date.before(new Date())) {
//                date = this.addDay(date, 1);
//                System.out.println(date);
//            }
//            Timer timer = new Timer();
//            NFDFlightDataTimerTask task = new NFDFlightDataTimerTask();
//            //安排指定的任务在指定的时间开始进行重复的固定延迟执行。
//            timer.schedule(task, date, PERIOD_DAY);
//        }
//        // 增加或减少天数
//        public Date addDay(Date date, int num) {
//            Calendar startDT = Calendar.getInstance();
//            startDT.setTime(date);
//            startDT.add(Calendar.DAY_OF_MONTH, num);
//            return startDT.getTime();
//        }
//    }

//    public  class NFDFlightDataTimerTask extends TimerTask {
//        private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        private  Logger log = LoggerFactory.getLogger(NFDFlightDataTimerTask.class);
//        @Override
//        public void run() {
//            try {
//                //在这里写你要执行的内容
//                msgSend1();
//                System.out.println("执行当前时间" + formatter.format(Calendar.getInstance().getTime()));
//            } catch (Exception e) {
//                log.info("-------------解析信息发生异常--------------");
//            }
//        }
//    }

}

